<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel" v-if="disableSubmit">关闭</a-button>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :label="'组织名称'" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            style="width: 100%"
            showSearch
            optionFilterProp="children"
            :autoClearSearchValue="false"
            v-decorator="['tenantId', validatorRules.tenant]"
            @change="changeTenant($event)"
            :getPopupContainer="(target) => target.parentNode">
            <a-select-option v-for="(item, index) in tenantList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            placeholder="请选择角色"
            mode="multiple"
            optionFilterProp="children"
            :autoClearSearchValue="false"
            style="width: 100%"
            v-decorator="['roles', validatorRules.roles]"
            :getPopupContainer="(target) => target.parentNode">
            <a-select-option v-for="(item, index) in roleList" :key="index" :value="item.id">
              {{ item.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-tree-select
            style="width: 100%"
            :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
            placeholder="请选择部门"
            showSearch
            treeNodeFilterProp="title"
            allow-clear
            treeDefaultExpandAll
            :tree-data="departTreeData"
            v-decorator="['departId', validatorRules.depart]"
            :getPopupContainer="(target) => target.parentNode"
            :multiple="true"
            @change="(departId, label, extra) => changeDepart(departId, label)">
          </a-tree-select>
        </a-form-item>
        <a-form-item label="负责部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            style="width: 100%"
            :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
            placeholder="请选择负责部门"
            allow-clear
            treeDefaultExpandAll
            mode="multiple"
            :getPopupContainer="(target) => target.parentNode"
            :options="departsTreeData"
            v-decorator="['departIds']">
          </a-select>
        </a-form-item>
        <a-form-item label="工号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入工号" v-decorator.trim="['workNo',validatorRules.workNo]"/>
        </a-form-item>
        <a-form-item label="职务" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            style="width: 100%"
            placeholder="请选择职务"
            showSearch
            optionFilterProp="children"
            :autoClearSearchValue="false"
            allowClear
            v-decorator="['positionId']"
            :getPopupContainer="(target) => target.parentNode">
            <a-select-option v-for="(item, index) in positionList" :key="index" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="showAdminFlag" label="是否超管" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-dict-select-tag :triggerChange="true" v-decorator="['userIdentity']" dictCode="is_admin"></j-dict-select-tag>
        </a-form-item>
        <a-form-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-image-upload class="appIconFile-uploader" text="上传" v-decorator="['avatar']" :disabled="disableSubmit"></j-image-upload>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import JImageUpload from '@/components/jeecg/JImageUpload';
  import pick from 'lodash.pick'
  import { queryByTenantId } from '../../position/service.js'
  import { checkUserTenant, queryTenantRole, queryTenantChildList, queryDepartByTenantId, addUserTenant, editUserTenant } from '../service'
  import { duplicateCheck } from '@api/api';

  export default {

    name: 'AppModal',
     components: {
      JImageUpload
    },
    data() {
      return {
        title: '操作',
        visible: false,
        disableSubmit: false,
        showAdminFlag: false,
        userId: '',
        tenantId: '',
        positionList: [],
        roleList: [],
        tenantList: [],
        departTreeData: [],
        departsTreeData: [],
        tenantMap: {},
        departIds: [], // 负责部门id
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        validatorRules: {
          tenant: { rules: [{ required: true, message: '请选择组织!' }, { validator: this.validateSameTenant }] },
          roles: { rules: [{ required: true, message: '请选择角色!' }] },
          // depart: { rules: [{ required: true, message: '请选择部门!' }] },
          workNo: { rules: [{ validator: this.validateWorkNo }] }
        },
        form: this.$form.createForm(this),
        url: {
        }

      }
    },
    created() {
    },
    computed: {
    },
    methods: {
      add(userId, tenantId) {
        this.edit({ userId: userId }, tenantId);
      },
      edit(record, tenantId) {
        let that = this;
        this.userId = record.userId;
        this.tenantId = tenantId;
        this.showAdminFlag = false;
        this.positionList = [];
        this.roleList = [];
        this.tenantList = [];
        this.departTreeData = [];
        this.departsTreeData = [];
        this.tenantMap = {};
        this.departIds = [];
        this.model = {};
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.model.departId = record.belongDepartIds ? record.belongDepartIds.split(',') : undefined;
        this.model.roles = record.roleIds ? record.roleIds.split(',') : undefined;
        this.model.departIds = record.departIds ? record.departIds.split(',') : undefined;
        this.model.positionId = record.post;

        this.visible = true;

        if (this.model.id) {
          this.initTenantList(async function () {
            await that.initialRoleList(that.model.tenantId);
            await that.initPositionList(that.model.tenantId);
            await that.initDepartList(that.model.tenantId);
            if (that.model.belongDepartIds) {
              that.changeDepart(that.model.belongDepartIds.split(','), that.model.departNames.split(','))
            } else {
              that.model.departIds = [];
            }
            if (that.positionList.filter(i => { return i.id === that.model.positionId }).length === 0) {
              that.model.positionId = null;
            }
            that.showAdminFlag = !that.tenantMap[that.model.tenantId].hasAdmin || that.tenantMap[that.model.tenantId].adminId === that.model.userId;
            that.$nextTick(() => {
              setTimeout(() => {
                that.form.setFieldsValue(pick(that.model, 'tenantId', 'roles', 'departId', 'departIds', 'workNo', 'positionId', 'userIdentity', 'avatar'));
              }, 5)
            })
          }, tenantId);
        } else {
          this.initTenantList(undefined, tenantId);
        }
      },
      initTenantList(event, tenantId) {
        queryTenantChildList(tenantId).then(res => {
          if (res.success) {
            this.tenantList = res.result
            this.tenantList.forEach((item) => {
              this.tenantMap[item.id] = item;
            })
            if (event) {
              event();
            }
          }
        })
      },
      changeTenant(tenantId) {
        this.tenantId = tenantId;
        this.initialRoleList(tenantId);
        this.initPositionList(tenantId);
        this.initDepartList(tenantId);
        this.departsTreeData = [];
        this.showAdminFlag = !this.tenantMap[tenantId].hasAdmin;
        setTimeout(() => {
          this.form.setFieldsValue({ roles: [], departIds: [], departId: [], positionId: null, userIdentity: 1, workNo: null });
        }, 5)
      },
      async initialRoleList(tenantId) {
        if (tenantId) {
          const res = await queryTenantRole(tenantId);
          if (res.success) {
            this.roleList = res.result;
          }
        } else {
          this.roleList = [];
        }
      },
      async initPositionList(tenantId) {
        if (tenantId) {
          const res = await queryByTenantId(tenantId)
            if (res.success) {
              this.positionList = res.result;
              if (this.positionList.length === 0) {
                this.form.setFieldsValue({ positionId: null });
              }
            }
        } else {
          this.positionList = [];
          this.form.setFieldsValue({ positionId: null });
        }
      },
      async initDepartList(tenantId) {
        if (tenantId) {
          const res = await queryDepartByTenantId(tenantId)
            if (res.success) {
              this.departTreeData = res.result
            }
        } else {
          this.departTreeData = []
        }
      },
      validateSameTenant(rule, value, callback) {
        if (!value) {
          callback()
        }
        let param = {
          tenantId: value,
          userId: this.userId,
          id: this.model.id
        }
        checkUserTenant(param).then((res) => {
          if (res.success) {
            callback();
          } else {
            callback('存在相同租户');
          }
        });
      },
      validateWorkNo(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 16) {
            var params = {
              tableName: 'sys_user_tenant',
              fieldName: 'work_no',
              fieldVal: value,
              tenantId: this.tenantId,
              dataId: this.model.id
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('工号已存在!')
              }
            })
          } else {
            callback('工号长度小于15个字符！')
          }
        }
      },
      changeDepart(departIds, labels) {
        let that = this
        this.form.resetFields('departIds', '');
        if (departIds && departIds.length > 0) {
          that.departsTreeData = [];
          departIds.forEach(function (item, i) {
            that.departsTreeData.push({ value: item, label: labels[i] })
          })
        } else {
          that.departsTreeData = [];
        }
      },
      close() {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let formData = Object.assign(this.model, values)
            formData.userId = that.userId;
            let obj;
             if (!this.model.id) {
              obj = addUserTenant(this.tenantId, formData);
            } else {
              obj = editUserTenant(this.tenantId, formData);
            }

            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
              that.close()
            })
          }
        })
      },
      handleCancel() {
        this.close()
      }
    }
  }
</script>

<style scoped>

</style>
